angular.module('services', []).factory('httpInterceptor', ['$q',function($q) {  
	// http请求前拦截器
	var requestInterceptor = {
			request: function(config) {
					try{
						config = config || {}; 
						config.headers = config.headers || {};
						config.headers['qs-pcversion'] = GLOBAL_DATA && GLOBAL_DATA.sysWebSystemVersion || '';
					} catch(e){}
					//document.currentLoginId在document.ready时取自cookie，如果用户在其他标签退出重新登录，cookie中的isLoginId会被刷新，此时旧页面再次发起ajax请求提示页面失效
					if (typeof(getCookie) === 'function' && getCookie('isLoginId') && document.CURRENT_LOGIN_ID && getCookie('isLoginId') != document.CURRENT_LOGIN_ID) {
			        	var canceler = $q.defer();
			        	config.timeout = canceler.promise;
			            canceler.resolve();
			            alert("当前页面已失效，请刷新或重新登录！");
			        }
					return config || $q.when(config);
				}
        };
        return requestInterceptor;
    }]).config(['$httpProvider', function($httpProvider) { 
        $httpProvider.interceptors.push('httpInterceptor');
        $httpProvider.defaults.withCredentials = true;
    }]).factory('httpServices',["$http",function($http) {
    
	// 提醒级别
	var REMIND_LEVEL = {
		normal: 'normal', // 正常模式(默认)
		silence: 'silence' // 静默模式
	};
    
	// 根据提醒级别输出信息
    var showAlert = function(message, level){
    	if(!level || !REMIND_LEVEL[level] || level == REMIND_LEVEL.normal){// 不传默认是alert
    		alert(message);
    	} else if(level == REMIND_LEVEL.silence){
    		console.error(message);
    	} else {
    		alert(message);
    	}
    }
    
    /**
     * 发送错误日志
     */
    var logError = function(data, status, headers, config) {
    	try{
	    	// 只记录生产环境的日志
	    	if (GL_CONS_ENV && GL_CONS_ENV.IS_PROD) {
	    		var errorInfo = "&app=is_pc&status=" + status + "&url=" + (config ? config.url : "");
	    		errorInfo += "&version=" + (GLOBAL_DATA && GLOBAL_DATA.sysWebSystemVersion || '') + "&device=" + (navigator ? navigator.appVersion : "");
				if (data) {
					var datastr = JSON.stringify(data);
					if (datastr.length > 2000) {
						datastr = datastr.substr(0, 2000);
					}
					errorInfo += "&data=" + datastr + "&statusCode=" + data.statusCode;
				}
				if(userLoginInfoJSON && userLoginInfoJSON.userVO) {
					errorInfo += "&cid=" + userLoginInfoJSON.userVO.cid + "&userId=" + userLoginInfoJSON.userVO.id;
				}
				$.ajax({
					url: '//qinsilk-log.cn-hangzhou.log.aliyuncs.com/logstores/error_report_log/track?APIVersion=0.6.0' + errorInfo,
					xhrFields: {withCredentials: true}
				});
	    	}
		} catch(e){}
    }
    
	// 请求错误处理
	var handleError = function(data, status, headers,
			config, remindLevel) {
		if (status === 500) {
			if (data && data.statusCode) {
				showAlert(data.content, remindLevel);
			} else {
				showAlert("服务器开了个小差！", remindLevel);
			}
		} else if (status === 403) {
			if (data && data.statusCode) {
				if (data.statusCode === 1403) { // 1403
					// 登陆超时
					showAlert(data.content, remindLevel);
				} else {
					// 1401 无权限 1404
					// 保存的对象已经被其他账号修改，请重新加载数据
					showAlert(data.content, remindLevel);
				}
			} else {
				showAlert("服务器开了个小差！", remindLevel);
			}
		} else {
			if(status != 0){
				showAlert("当前网络不可用！(" + status + ")", remindLevel);
			}
		}
		
		logError(data, status, headers, config);
	};
	
	var httpPost = function(ac, data, config, remindLevel) {
		var target = getEvtTarget();
		disableTarget(target,true);
		return $http.post(ac, data, config).error(function(data, status, headers, config){
					disableTarget(target,false);
					handleError(data, status, headers, config, remindLevel);
				}).success(function(){
					disableTarget(target,false);
				});
	};
	var httpGet = function(ac, data, config, remindLevel) {
		var target = getEvtTarget();
		disableTarget(target,true);
		return $http.get(ac, data, config).error(function(data, status, headers, config){
			disableTarget(target,false);
			handleError(data, status, headers, config, remindLevel);
		}).success(function(){
			disableTarget(target,false);
		});
	};

	return {
		post : httpPost,
		postEncode : function(ac,param){
			return httpPost(ac,$.param(param), {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            });
		},
		get : httpGet,
		REMIND_NORMAL: REMIND_LEVEL.normal,
		REMIND_SILENCE: REMIND_LEVEL.silence
	};

} ]);

function disableTarget(target, isdisable, isclear) {
		if (target && target.tagName == "BUTTON") {
			try {
				// 重置对象状态
				if (isclear) {
					target.disabled = isdisable;
					target.value = 0;
				}
				//禁用按钮
				if (isdisable) {
					target.value++;
					target.disabled = isdisable;
				} else {
					if (target.value > 0) {
						target.value--;
					}
					//同一个按钮触发多次请求后台时，只有全部返回才可用
					if (target.value <=0) {
						target.disabled = isdisable;
					} 
				}
			} catch(e){
			}
		}
	}
//兼容ie获取event的触发对象
function getEvtTarget() {
	return window.event ? (event.target ? event.target : event.srcElement):null;
}
